#include"../usr_include/Detect.h"
#include"../lib_include/Logger.h"
#include "../lib_include/Timestamp.h"

using std::placeholders::_1;
using std::placeholders::_2;
using std::placeholders::_3;

Detect::Detect(netlib::net::EventLoop* loop, const netlib::net::InetAddress& listenAddr)
				: _server(loop, listenAddr, "Detect"), sql("localhost", "root", "qweasd", "test")
{
	_server.setConnectionCallback(std::bind(&Detect::onConnection, this, _1));
	_server.setMessageCallback(std::bind(&Detect::onMessage, this, _1, _2, _3));
}

void Detect::start()
{
	_server.start();
}

void Detect::onConnection(const netlib::net::TcpConnectionPtr& conn)
{
	LOG_INFO << "EchoServer - " << conn->peerAddress().toIpPort() << " -> "
			<< conn->localAddress().toIpPort() << " is "
			<< (conn->connected() ? "UP" : "DOWN");
}

void Detect::onMessage(const netlib::net::TcpConnectionPtr& conn,
						netlib::net::Buffer* buf,
						netlib::Timestamp time)
{
	netlib::string t_msg(buf->retrieveAllAsString());
	if(!t_msg.empty())
		dosomething(t_msg);
	conn->send(t_msg);
}

void Detect::dosomething(netlib::string& msg)
{
	LOG_INFO << "recv: " << msg.c_str();
	const char* str = msg.c_str();
	if(strncasecmp(str, "Transaction:", 12) != 0)
	{
		msg="error msg";
		LOG_INFO<<"error msg";
		return;
	}
	str+=12;
	const char* tmp = strchr(str, ':');
	int num = tmp - str;
	switch(num)
	{
		case 5:     { dologin(++tmp, msg); break; }
		case 10:    { doregistered(++tmp, msg); break; }
		case 6:     { doquery(++tmp, msg); break; }
		case 4:     { dopost(++tmp, msg); break; }
		case 7:     { dorefresh(++tmp, msg); }
	}
	// LOG_INFO << "send: " << msg.c_str();
}

void Detect::dologin(const char* str, netlib::string& msg)
{
	char uname[20]={0}, upwd[20]={0};
	const char* tmp = strchr(str, ':');
	strncpy(uname, str, tmp-str);
	str = tmp+1;
	tmp = strchr(str, '^');
	strncpy(upwd, str, tmp-str);
	char sqlstr[80] = {0};
	sprintf(sqlstr, "select upwd from usrinfo where uname=\"%s\"", uname);
	results res = sql.Query(sqlstr);
	if(res.empty())
		msg="nouser";
	else if(strcasecmp(res[0][0].c_str(), upwd)==0)
		msg="loginsuccessful";
	else
		msg="pwderrno";
}

void Detect::doregistered(const char* str, netlib::string& msg)
{
	char uname[20]={0}, upwd[20]={0};
	const char* tmp = strchr(str, ':');
	strncpy(uname, str, tmp-str);
	str = tmp+1;
	tmp = strchr(str, '^');
	strncpy(upwd, str, tmp-str);
	char sqlstr[80] = {0};
	sprintf(sqlstr, "select upwd from usrinfo where uname=\"%s\"", uname);
	results res = sql.Query(sqlstr);
	if(res.empty())
	{
		memset(sqlstr, '\0', 80);
		sprintf(sqlstr, "insert into usrinfo (uname,upwd) value(\"%s\", \"%s\")", uname, upwd);
		if(sql.Modify(sqlstr))
			msg = "newusersuccessful";
		else
			msg = "registeredfalse";
	}
	else if(!res.empty())
		msg="repeatuser";
	else
		msg="error";
}

void Detect::doquery(const char* str, netlib::string& msg)
{
	char sqls[80] = {0};
	strcpy(sqls, str);
	sqls[strlen(str)-1] = '\0';
	netlib::string sqlsend = "Transaction:querys:";
	results res = sql.Query(sqls);
	if(res.empty())
		msg="no find";
	else
	{
		for(auto &r : res[0])
		{
			sqlsend += r;
			sqlsend += ":";
        }
		sqlsend[sqlsend.size()-1] = '^';
		msg = sqlsend;
	}
}

void Detect::dorefresh(const char* str, netlib::string& msg)
{
	char sqlstr[80] = {0};
	netlib::string refreshd = "Transaction:";
	for(int i=1;i<4;i++)
	{
		refreshd += "equip_";
		refreshd += std::to_string(i);
		refreshd += ":";
		sprintf(sqlstr, "select * from equip_%d order by uptime desc", i);
		results res = sql.Query(sqlstr);
		if(!res.empty())
		{
			for(auto &r : res[0])
			{
				refreshd += r;
				refreshd += ":";
			}
		}
	}
	refreshd[refreshd.size()-1] = '^';
	msg = refreshd;
}

void Detect::dopost(const char* str, netlib::string& msg)
{
	char sqlstr[100] = {0};
	netlib::Timestamp time(netlib::Timestamp::now());
	char tmp[10] = {0}, ph[10] = {0}, oxy[10], ion[10] = {0};

	const char* tp = strchr(str,':');
	strncpy(tmp, str, tp-str);
	str = tp + 1;
	tp = strchr(str,':');
	strncpy(ph, str, tp-str);
	str = tp + 1;
	tp = strchr(str,':');
	strncpy(oxy, str, tp-str);
	str = tp + 1;
	tp = strchr(str,'^');
	strncpy(ion, str, tp-str);
	
	if (ion)
		sprintf(sqlstr, "insert into equip_1 (temperature,ph,oxygen,ion,uptime) values (%s,%s,%s,%s,'%s')",tmp,ph,oxy,ion,time.toFormattedString(false).c_str());
	
	sql.Modify(sqlstr);
}
